#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "aes128.h"


#define DEBUG_TEST qDebug()


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->textEdit_File,SIGNAL(textChanged()),this,SLOT(textview_file_changed()));
    //count = 3;
    tableWidget_DevInfo_Init();
    ScanHD();
    tableWidget_DevInfo_Update();
    createEncryptedArea();
}

MainWindow::~MainWindow()
{
    delete ui;
}

char MainWindow::FirstDriveFromMask(ULONG unitmask)
{
    char i;
    for (i = 0; i < 26; ++i)
    {
        if (unitmask & 0x1)
            break;
        unitmask = unitmask >> 1;
    }
    return (i + 'A');
}

//=================================================================================
//系统启动扫描已经连接的U盘 程序只会在系统执行时执行一次
//=================================================================================
void MainWindow::ScanHD()
{
    DEBUG_TEST<<"U盘扫描";
    char diskPath[5] = { 0 };
    DWORD allDisk = GetLogicalDrives(); //返回一个32位整数，将他转换成二进制后，表示磁盘,最低位为A盘
    udisk_lists.clear();
    if (allDisk!=0)
    {
        for (int i=0;i<26;i++)     //假定最多有12个磁盘从A开始计数
        {
            if ((allDisk & 1)==1)
            {
                sprintf( diskPath, "%c", 'A'+i );
                strcat( diskPath, ":" );
                LPCWSTR RootPathName =(LPCWSTR)QString(diskPath).utf16();
                //DEBUG_TEST<<"盘符： "<<diskPath << GetDriveType(RootPathName);
                if (GetDriveType(RootPathName) ==  DRIVE_REMOVABLE)
                {
                    QString  path(diskPath);
                    //this->AddDisk(path);
                    udisk_list_t udisk_tmp;
                    udisk_tmp.udisk_path = path;
                    udisk_tmp.is_check = true;
                    if( GetVolumeInformation(RootPathName,0,0,0,0,0,0,0) ) //判断驱动是否准备就绪
                    {
                       DEBUG_TEST<<"U盘准备就绪！"<<diskPath;
                       append_log("U盘准备就绪！" + path);
                       udisk_tmp.is_ready = true;
                    }
                    else
                    {
                        DEBUG_TEST<<"U盘未就绪！"<<diskPath;
                        append_log("U盘未就绪！"+path);
                        udisk_tmp.is_ready = false;
                    }
                    udisk_lists.append(udisk_tmp);
                    break;
                }
                //break;
            }
            allDisk = allDisk>>1;
        }
     }
}

bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    MSG* msg = reinterpret_cast<MSG*>(message);
    int msgType = msg->message;
    if(msgType==WM_DEVICECHANGE)
    {
        PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam;
        switch (msg->wParam) {
        case DBT_DEVICEARRIVAL:

            if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)
            {
                PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
                if(lpdbv->dbcv_flags ==0)
                {
                    QString USBDisk = QString(this->FirstDriveFromMask(lpdbv ->dbcv_unitmask));
                    DEBUG_TEST << "USB_Arrived and The USBDisk is: "<<USBDisk ;
                    append_log("USB_Arrived and The USBDisk is: "+USBDisk );
                    ScanHD();
                    tableWidget_DevInfo_Update();
                }
            }
            break;
        case DBT_DEVICEREMOVECOMPLETE:
            if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)
            {
                PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
                if(lpdbv->dbcv_flags == 0)
                {
                    DEBUG_TEST << "USB_Removed";
                    QString USBDisk;
                    USBDisk = QString(this->FirstDriveFromMask(lpdbv ->dbcv_unitmask));
                    USBDisk += ":";
                    append_log("USB_Removed and The USBDisk is: "+ USBDisk );
                    //this->DeleteDisk(USBDisk);
                    DEBUG_TEST<<"this-delete is ="<<USBDisk;

                    ScanHD();
                    tableWidget_DevInfo_Update();
                }
            }
            break;
        }
    }

    return false;
}

void MainWindow::tableWidget_DevInfo_Init()
{
    ui->tableWidget_DevInfo->setRowCount(2);
    ui->tableWidget_DevInfo->setColumnCount(3);
    //设置表头字体加粗
    QFont font = ui->tableWidget_DevInfo->horizontalHeader()->font();
    font.setBold(true);
    ui->tableWidget_DevInfo->horizontalHeader()->setFont(font);
    QStringList header;
    header <<"选择操作"<<"可移动磁盘"<<"格式化";
    ui->tableWidget_DevInfo->setHorizontalHeaderLabels(header);
//    ui->tableWidget_DevInfo->resizeColumnsToContents();    //自适应宽度
    ui->tableWidget_DevInfo->setColumnWidth(0,100);
    ui->tableWidget_DevInfo->setColumnWidth(1,160);
    ui->tableWidget_DevInfo->setColumnWidth(2,100);

    ui->tableWidget_DevInfo->show();
}
void MainWindow::tableWidget_DevInfo_Update()
{
    int row = udisk_lists.length();
    //ui->tableWidget_DevInfo->clear();//此处会清表头
    ui->tableWidget_DevInfo->clearContents();
    ui->tableWidget_DevInfo->setRowCount(row+1);
    for(int i=0; i<row; i++)
    {
        if(udisk_lists[i].is_ready)
            ui->tableWidget_DevInfo->setItem(i, 1, new QTableWidgetItem(udisk_lists[i].udisk_path + "    准备就绪!"));
        else
            ui->tableWidget_DevInfo->setItem(i, 1, new QTableWidgetItem(udisk_lists[i].udisk_path + "    未就绪!"));

        QCheckBox *ischeck = new QCheckBox();
        connect(ischeck,SIGNAL(clicked()),this,SLOT(tableWidget_DevIsChecked()));

        if(udisk_lists[i].is_check == true)
            ischeck->setCheckState (Qt::Checked);
        else
            ischeck->setCheckState (Qt::Unchecked);
        ui->tableWidget_DevInfo->setCellWidget(i,0,ischeck);


    }
}

void MainWindow::createEncryptedArea()
{
    if(udisk_lists[0].is_check == true)
    {
        QString dir_str = udisk_lists[0].udisk_path+"//EnencryptedArea";
        QString passworddir = dir_str+"/password.txt";
        QDir dir;
        if (!dir.exists(dir_str))
            {
                bool res = dir.mkpath(dir_str);
                qDebug() << "新建目录是否成功" << res;
                if (res){
                    bool isOK;
                    QString text = QInputDialog::getText(this, "Set Password",
                                                                "Please input your password",
                                                                QLineEdit::Normal,
                                                                "your password",&isOK);
                    if(isOK) {
                           QMessageBox::information(this, "Success", "Set Password Successfully"+text,
                                                                        QMessageBox::Yes | QMessageBox::No,
                                                                        QMessageBox::Yes);
                            //passworddir = dir_str+"/password.txt";
                            QFile file(passworddir);
                            file.open(QIODevice::ReadWrite);
                            QString md5_pass = MD5(text);
                            file.write(md5_pass.toLatin1(),md5_pass.length());
                            file.close();

                            SetFileAttributes((LPCWSTR)passworddir.unicode(),FILE_ATTRIBUTE_HIDDEN);
                    }
                }
            }
        else{
            //待添加功能
        }
    }
}

void MainWindow::tableWidget_DevIsChecked()
{
    QCheckBox *senderObj=qobject_cast<QCheckBox*>(sender());
    if(senderObj == NULL)
    {
        return;
    }
    QModelIndex idx = ui->tableWidget_DevInfo->indexAt(QPoint(senderObj->frameGeometry().x(),senderObj->frameGeometry().y()));
    int row=idx.row();
    int col=idx.column();
    // 其他响应信息......
    udisk_lists[row].is_check = senderObj->isChecked();
    DEBUG_TEST << "tableWidget_DevInfo is "<< senderObj->isChecked() << row << col;
}

bool MainWindow::fomat_udisk(QString udisk_path)
{
    QString program = "cmd.exe";
    QStringList arguments;
    arguments << "/c"<< "format " + udisk_path +" /FS:FAT32 /Q /Y";
    DEBUG_TEST << program << arguments;

    QProcess p;
    p.start(program, arguments);
    if (p.waitForStarted())
    {
        p.waitForFinished();

        DEBUG_TEST << QString::fromLocal8Bit(p.readAllStandardOutput());
        return true;
    }
    else
    {
        DEBUG_TEST << "Failed to start";
        return false;
    }
}

void MainWindow::append_log(QString log)
{
    ui->textEdit_Log->append(log);
}

void MainWindow::on_pushButton_Update_clicked()
{
    ScanHD();
    tableWidget_DevInfo_Update();
}

void MainWindow::on_pushButton_Show_clicked()
{
    if (udisk_lists.length() == 0){
        QMessageBox::warning(this, "Warning", "没有识别到U盘");
        return;
    }
    Dialog *MyDialog = new Dialog(udisk_lists[0].udisk_path);
    MyDialog->show();
//    QString program = "explorer";
//    QStringList arguments;
//    int udisk_n = udisk_lists.length();
//    for(int i=0; i<udisk_n; ++i)
//    {
//        if(udisk_lists[i].is_check)
//        {
//            arguments.clear();
//            arguments << udisk_lists[i].udisk_path;
//            DEBUG_TEST << program << arguments;

//            QProcess p;
//            p.start(program, arguments);
//            if (p.waitForStarted())
//            {
//                p.waitForFinished();

//                DEBUG_TEST << QString::fromLocal8Bit(p.readAllStandardOutput());
//            }
//            else
//            {
//                DEBUG_TEST << "Failed to start";
//            }
//        }
//    }
}

void MainWindow::on_pushButton_Formater_clicked()
{
    int row = udisk_lists.length();
    append_log("开始格式化");
    for(int i=0; i<row; i++)
    {
        ui->tableWidget_DevInfo->setItem(i, 2, new QTableWidgetItem(""));
        if(udisk_lists[i].is_check == true)
        {
            ui->tableWidget_DevInfo->setItem(i, 2, new QTableWidgetItem("开始格式化"));
            bool result = fomat_udisk(udisk_lists[i].udisk_path);
            if(result)
            {
                ui->tableWidget_DevInfo->setItem(i, 2, new QTableWidgetItem("格式化成功"));
                append_log(udisk_lists[i].udisk_path + " 格式化成功");
            }
            else
            {
                ui->tableWidget_DevInfo->setItem(i, 2, new QTableWidgetItem("格式化失败"));
                append_log(udisk_lists[i].udisk_path + " 格式化失败");
            }
        }
    }
}

QString MainWindow::MD5(QString password)
{
    QByteArray byteArray;
    byteArray.append(password);
    QByteArray hash = QCryptographicHash::hash(byteArray, QCryptographicHash::Md5);
    QString strMD5 = hash.toHex();
    return strMD5;
}

void MainWindow::textview_file_changed()
{
        QString allfile = ui->textEdit_File->toPlainText();
        //qDebug() << ui->textEdit_File->toPlainText() << endl;
        //return;
        QStringList lst = allfile.split('\n');
        qDebug() << lst << endl;
        //if (lst.length()==0) return;
        QString newfile = lst[lst.length()-1];
        QString newfile_path;
        if (newfile.contains("///"))
            newfile_path = newfile.split("///")[1];
        else
            newfile_path = newfile;
        QString newfile_at_Upan_path = udisk_lists[0].udisk_path+"/EnencryptedArea/"+newfile_path.split('/')[newfile_path.split('/').length()-1];
        //qDebug() << newfile_path << ' ' << newfile_at_Upan_path << endl;
        if (!QFileInfo::exists(newfile_path)) return;
        QFileInfo fileInfo(newfile_path);
        if (fileInfo.isDir()){
            if(!QDir(newfile_path).exists())
            {
                int decision = QMessageBox::warning(
                            NULL, tr("Warning"),
                            "\"" + newfile_path.split('/')[newfile_path.split('/').length()-1] + "\" " + tr("already exists.\nWould you like to overwrite the file?"),
                            QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
                if (decision == QMessageBox::Yes){
                    copyRecursively(newfile_path, newfile_at_Upan_path);
                }
            }
            else
                copyRecursively(newfile_path, newfile_at_Upan_path);
                //qCopyDirectory(QDir(newfile_path), QDir(newfile_at_Upan_path), 1);
                //qDebug() << "Dir success" << endl;
        }
        else
        {
            if (QFile::exists(newfile_at_Upan_path)){
                int decision = QMessageBox::warning(
                            NULL, tr("Warning"),
                            "\"" + newfile_path.split('/')[newfile_path.split('/').length()-1] + "\" " + tr("already exists.\nWould you like to overwrite the file?"),
                            QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
                if (decision == QMessageBox::Yes){
                    QFile::remove(newfile_at_Upan_path);
                    //copyfile(newfile_path, newfile_at_Upan_path);
                    file_encrypt(newfile_path, newfile_at_Upan_path);
                }
            }
            else{
                //copyfile(newfile_path, newfile_at_Upan_path);
                file_encrypt(newfile_path, newfile_at_Upan_path);
                //QFile::remove(newfile_at_Upan_path);
            }
        }

        disconnect(ui->textEdit_File,SIGNAL(textChanged()),this,SLOT(textview_file_changed()));
        ui->textEdit_File->setText(allfile+"\n");
        connect(ui->textEdit_File,SIGNAL(textChanged()),this,SLOT(textview_file_changed()));
}

void MainWindow::copyfile(QString newfile_path, QString newfile_at_Upan_path)
{
    QFile::copy(newfile_path, newfile_at_Upan_path);
}

bool MainWindow::copyRecursively(const QString &srcFilePath,
                            const QString &tgtFilePath)
{
    QFileInfo srcFileInfo(srcFilePath);
    if (srcFileInfo.isDir()) {
        QDir targetDir(tgtFilePath);
        targetDir.cdUp();
        qDebug() << QFileInfo(tgtFilePath).fileName() << endl;
        if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName()))
            return false;
        QDir sourceDir(srcFilePath);
        QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
        foreach (const QString &fileName, fileNames) {
            const QString newSrcFilePath
                    = srcFilePath + QLatin1Char('/') + fileName;
            const QString newTgtFilePath
                    = tgtFilePath + QLatin1Char('/') + fileName;
            if (!copyRecursively(newSrcFilePath, newTgtFilePath))
                return false;
        }
    } else {
        file_encrypt(srcFilePath, tgtFilePath);
//        if (!QFile::copy(srcFilePath, tgtFilePath))
//            return false;
//        else
//        {
//            file_encrypt(srcFilePath, tgtFilePath);
//            //QFile::remove(tgtFilePath);
//        }
    }
    return true;
}

inline static int char2int(char c) {
    int result = (int) c;
    return result & 0x000000ff;
}
void print_ASSCI(char *s, int length) {
    for (int i = 0; i < length; i++)
        printf("0x%x ", char2int(s[i]));
    printf("\n");
}

void MainWindow::file_encrypt(QString FilePath, QString target)
{
    const int BUFFER_SIZE = 25000000;
    char key[] = "abcdabcdabcdabcd";
    char* buffer = new char[BUFFER_SIZE];
    std::string filename_ = FilePath.toStdString();
    std::string target_address_ = target.toStdString();
    const char* filename = filename_.c_str();
    const char* target_address = target_address_.c_str();
    FILE* file = fopen(filename, "rb");
    if (!file) {
        // error
    } else {
        int value = fread(buffer, sizeof(char), BUFFER_SIZE, file);
        qDebug() << value;
        int to_add_length = 16 - value % 16;
        for (int i = value; i < (value / 16 + 1) * 16; i++) {
            buffer[i] = char(to_add_length);
        }
        aes_encrypt(buffer, value + to_add_length, key);
        FILE* to_write = std::fopen(target_address, "a+b");
        if (!to_write) {
            // error
        } else {
//            print_ASSCI(buffer, value + to_add_length);
            int result = std::fwrite(buffer, sizeof(char), value + to_add_length, to_write);
            qDebug() << result;
            qDebug() << buffer;
//            printf("%d\n", result);
        }
        std::fclose(to_write);
    }
    std::fclose(file);
    delete buffer;
}

void MainWindow::file_decrypt(QString FilePath, QString target)
{
    const int BUFFER_SIZE = 25000000;
    char key[] = "abcdabcdabcdabcd";
    char* buffer = new char[BUFFER_SIZE];
    std::string filename_ = FilePath.toStdString();
    std::string target_address_ = target.toStdString();
    const char* filename = filename_.c_str();
    const char* target_address = target_address_.c_str();
    FILE* file = fopen(filename, "rb");
    if (!file) {
        // error
    } else {
        int value = fread(buffer, sizeof(char), BUFFER_SIZE, file);
        memset(buffer + value, '\0', 1);
        aes_decrypt(buffer, value, key);
        int added_length = int(buffer[value - 1]);
        memset(buffer + value - added_length, '\0', 1);
        std::FILE* to_write = std::fopen(target_address, "a+b");
        if (!to_write) {
            // error
        } else {
            std::fwrite(buffer, sizeof(char), value - added_length, to_write);
        }
        std::fclose(to_write);
    }
    std::fclose(file);
    delete buffer;
}

